<?php

namespace Biz\service\activity\project;

use Biz\cache\activity\CBizProject;
use Biz\model\activity\BizProjectCustomerModel;
use Biz\model\activity\BizProjectGroupModel;
use Biz\model\activity\BizProjectResponsibilityModel;
use Doraemon\model\Admin\BeerUsUser;
use Doraemon\model\Admin\BeerUsUser as AdminUsers;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Exception;
use Hhz\AdministrativeRegion\Region;

class BizProjectCustomer extends BizProjectPageTpl
{

    const TPL_CONFIG_TPL_NAME = '客户服务档案';

    public function exportDisplay()
    {
        $list = $this->getExportList();
        $header = [
            '客户ID',	'所属销售',	'品牌名称',	'客户所属区域',	'客户地理位置',	'客户基础信息',	'客户特征',	'更新时间',
        ];
        $rows = [$header];
        foreach ($list as $v) {
            $rows[] = [
                $v['id'],
                implode(',', $v['sellers']),
                $v['name'],
                $this->useNameOptions($v['customer_area'], BizProjectProject::CUSTOMER_AREA_MAP),
                $v['customer_area_code'],
                $v['customer_intro'],
                $v['customer_features'],
                $v['updated_at'],
            ];
        }
        $instance = \Biz\service\activity\project\ExportToolsBizProject::getInstance();
        $instance::create(date("YmdHis") . '客户服务档案列表', $rows);
    }

    public function getTotal(): int
    {
        return BizProjectCustomerModel::statusTotal($this->getRequestCondition());
    }

    public function getList(): array
    {
        $condition = ['ORDER' => ['id' => 'DESC']] + $this->getLimitCondition() + $this->getRequestCondition();
        $list = BizProjectCustomerModel::dataSelect( BizProjectCustomerModel::statusCondition() + $condition);
        $format = [];
        if (empty($list)) return $format;
        $ids = array_column($list, 'id');
        $responsible = BizProjectResponsibilityModel::findAdminByProjectId($ids, BizProjectResponsibilityModel::RESPONSIBILITY_MODULE_CUSTOMER);
        $admin_ids = BizProjectResponsibilityModel::afterFindAdmin();
        BeerUsUser::getNameByUsername($admin_ids);
        $areaMap = Region::getAllAreaDetail();
        foreach ($list as $v) {
            $tempResponsible = $responsible[$v['id']] ?? [];
            $format[] = [
                'id' => $v['id'],
                'sellers' => BeerUsUser::afterGetRowsMap($tempResponsible['seller'] ?? []),
                'name' => $v['name'],
                'customer_area' => $v['customer_area'],
                'customer_area_code' => $areaMap[$v['customer_area_code']] ?? '',
                'updated_at_date' => $v['updated_at'],
            ] + $v;
        }
        return $format;
    }

    public function condition(): array
    {
        $name = $this->getRequest()->input('name', '');
        $customer_area = $this->getRequest()->input('customer_area', '');
        $sellers = $this->getRequest()->input('sellers', '');

        $condition = [];
        if (strlen($name)) $condition['name[~]'] = $name;
        if ($customer_area) $condition['customer_area'] = $customer_area;
        if ($sellers) {
            BizProjectResponsibilityModel::findProjectByAdmin($sellers, BizProjectResponsibilityModel::RESPONSIBILITY_MODULE_CUSTOMER);
            $findProject = BizProjectResponsibilityModel::afterFindProject();
            if ($findProject) {
                $condition['id'] = $findProject;
            } else {
                $condition['id'] = 0;
                return $condition;
            }
        }

        //权限
        if (!$this->isAdmin()) {
            $findProject = self::findIds($this->adminId());
            $temp['id'] = $findProject ?: 0;
            $condition['OR #auth'] = $temp;
        }

        return $condition;
    }

    public static function findIds($adminId): array
    {
        return self::findAuthModuleIds($adminId, BizProjectResponsibilityModel::RESPONSIBILITY_MODULE_CUSTOMER);
    }

    private function searchKey(): string
    {
        return $this->adminId() . ":customer";
    }

    public function getGrid(Grid $grid)
    {
        $grid->filter(function (Grid\Filter $filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->equal('sellers', '所属销售')->multipleSelect(AdminUsers::getNameByUsername());
                $filter->equal('name', '客户名称');
            });//所属销售
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->equal('customer_area', '客户所属区域')->multipleSelect(BizProjectProject::CUSTOMER_AREA_MAP);
            });
            if ($this->getRequestCondition()) $filter->expand();
        });
        $grid->tools(function (Grid\Tools $tool) {
            $this->genExportButton($tool);
        });
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->column('id', '客户ID');
        $grid->column('sellers', '所属销售')->label();
        $grid->column('name', '品牌名称');
        $grid->column('customer_area', '客户所属区域')->using(BizProjectProject::CUSTOMER_AREA_MAP);
        $grid->column('customer_area_code', '客户地理位置');
        $grid->column('updated_at_date', '更新时间');
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
        });
    }

    public function getForm(Form $form)
    {
        $nameOptions = AdminUsers::getActiveNameByIds();
        $form->confirm('确定提交吗？');
        $form->text('name', '品牌名称')->attribute('maxlength', '50')->required();
        $form->multipleSelect('sellers', '所属销售')->options($nameOptions)->default([$this->adminId()])->required();
        $form->radio('customer_area', '客户所属区域')->options(BizProjectProject::CUSTOMER_AREA_MAP)->required();
        $form->select('customer_area_code', '客户地理位置')->options(Region::getAllAreaDetail())->required();
        $form->textarea('customer_intro', '客户基础信息')->help("品牌资料、组织架构、对接人性格、对接注意事项等")->attribute('maxlength', '500')->required();
        $form->textarea('customer_features', '客户特征')->help("销售区域、业务状况等")->attribute('maxlength', '500')->required();
        $form->disableReset();
    }

    public function getFormInfo($id)
    {
        $info = $id ? BizProjectCustomerModel::get('*', ['id' => $id]) : [];
        if ($info) {
            $sellers = BizProjectResponsibilityModel::findAdminByProjectId($info['id'], BizProjectResponsibilityModel::RESPONSIBILITY_MODULE_CUSTOMER);
            $info['sellers'] = $sellers['seller'] ?? [];
        }
        return $info;
    }

    public function hasAuthor($id): bool
    {
        if ($id == 0) return true;
        $authAdminId = self::findIds($this->adminId());
        return in_array($id, $authAdminId);
    }

    /**
     * @throws Exception
     */
    public function save($input)
    {
        $name = $input['name'] ?? '';
        $sellers = $input['sellers'] ?? [];
        $customer_intro = $input['customer_intro'] ?? '';
        $customer_features = $input['customer_features'] ?? '';
        $customer_area = $input['customer_area'] ?? 0;
        $customer_area_code = $input['customer_area_code'] ?? 0;
        $id = $input['id'] ?? 0;
        $old = BizProjectCustomerModel::get('id', ['name' => $name] + BizProjectCustomerModel::statusCondition());
        if ($old && $old != $id) throw new Exception("品牌名称 [{$name}] 已经存在");
        if (!$this->hasAuthor($id)) throw new Exception("仅客户所属销售、销售leader 可编辑");
        $addData = compact('customer_intro', 'customer_area', 'customer_features', 'customer_area_code', 'name', 'id');
        BizProjectCustomerModel::action(function () use ($id, $addData, $sellers) {
            $rs = BizProjectCustomerModel::addData(['updated_at' => date('Y-m-d H:i:s')] + $addData);
            if (!$rs) throw new Exception('客户服务档案主表保存失败');
            $id = $id ?: BizProjectCustomerModel::id();
            $exists = BizProjectResponsibilityModel::existsList($id, BizProjectResponsibilityModel::RESPONSIBILITY_MODULE_CUSTOMER);
            $find = [];
            foreach ($exists as $v) {
                $find[$v['admin_id']] = $v;
            }
            $rows = [];
            foreach ($sellers as $admin_id) {
                if (empty($admin_id)) continue;
                if (isset($find[$admin_id])) {
                    $status = $find[$admin_id]['status'];
                    if (!BizProjectResponsibilityModel::isNormal($status)) {
                        $rows[] = ['id' => $find[$admin_id]['id'], 'status' => BizProjectResponsibilityModel::normalStatus()];
                    }
                    unset($find[$admin_id]);
                } else {
                    $rows[] = ['project_id' => $id, 'type' => BizProjectResponsibilityModel::RESPONSIBILITY_TYPE_SELLER, 'module' => BizProjectResponsibilityModel::RESPONSIBILITY_MODULE_CUSTOMER,'admin_id' => $admin_id];
                }
            }
            foreach ($find as $item) {
                if (BizProjectResponsibilityModel::isNormal($item['status'])) {
                    $rows[] = ['id' => $item['id'], 'status' => BizProjectResponsibilityModel::delStatus()];
                }
            }

            foreach ($rows as $row) {
                BizProjectResponsibilityModel::addData($row);
            }
        });
    }

    /**
     * @throws Exception
     */
    public function delete($id)
    {
        if (!$this->isAdmin()) throw new Exception("仅管理员可操作");
        BizProjectCustomerModel::statusDelete($id);
    }

    public function breadcrumb(): array
    {
        return [
            [
                'text' => BizProjectProject::getListTitle(), 'url' => BizProjectProject::getRoute()->getListRoute()
            ],
        ];
    }
}